package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.*;
import com.baidu.mapapi.search.poi.*;
import com.lzx.iteam.adapter.LegworkAddressListAdapter;
import com.lzx.iteam.adapter.LegworkRecordListAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.AddressData;
import com.lzx.iteam.bean.LegworkRecordData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.LegworkListMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.LocationUtil;
import com.lzx.iteam.util.NetworkUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.radius;
import static com.lzx.iteam.ScheduleManagerActivity.mSelectPosition;

/**
 * Created by Megan on 16/9/1.
 */
public class LegworkMainActivity extends MyBaseActivity implements OnGetPoiSearchResultListener, View.OnClickListener, AbsListView.OnScrollListener {

    private String Tag = "LegworkMainActivity";
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.mv_legwork_main_mapview)
    MapView mMapView;
    @FindViewById(id = R.id.rl_legwork_main_layout1)
    RelativeLayout mRlLayout1;
    @FindViewById(id = R.id.rl_legwork_main_layout2)
    LinearLayout mRlLayout2;
    @FindViewById(id = R.id.ll_legwork_main_layout)
    LinearLayout mLlRoot;
    @FindViewById(id = R.id.ll_legwork_main_search_layout)
    LinearLayout mLlSearchLayout;
    @FindViewById(id = R.id.ll_legwork_main_search_layout_click)
    LinearLayout mLlSearch;
    @FindViewById(id = R.id.tv_legwork_main_current_address)
    TextView mTvCAddress;
    @FindViewById(id = R.id.tv_legwork_main_other_address)
    TextView mTvOtherAddress;
    @FindViewById(id = R.id.lv_legwork_main_sign_record_list)
    ListView mLvRecord;
    @FindViewById(id = R.id.lv_legwork_main_address_list)
    ListView mLvAddress;
    @FindViewById(id = R.id.iv_legwork_main_current_address_sign_in)
    ImageView mIvSign;

    private TextView mFooterText;
    private LinearLayout mFooterLayout;
    private ProgressBar mFooterProgress;
    boolean is_scrolling = false;   // 是否还在滚动
    private int pageIndex = 1;      // 加载的页数
    private int pageSize = 20;
    private int count;
    BaiduMap mBaiduMap;
    private GeoCoder geoCoder;
    private LocationUtil mLocationUtil;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private PoiSearch mPoiSearch = null;
    private String address = "";
    private double longitude;
    private double latitude;

    private final int MAP_SEARCH = 100;
    private final int REQUEST_CODE_SIGN = 111;
    private LegworkAddressListAdapter mAddressListAdapter;
    private LegworkRecordListAdapter mRecordListAdapter;
    private ArrayList<AddressData> mAddressDatas = new ArrayList<AddressData>();
    private ArrayList<LegworkRecordData> mRecordDatas;
    private String mGroupId;
    private String mFormId;
    private int flag;//0:普通  1:更新

    private final int GET_LEGWORK_LIST_MSG = 1000;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_LEGWORK_LIST_MSG:
                    if (msg.arg1 == 0) {
                        mRecordDatas = (ArrayList<LegworkRecordData>) msg.obj;
                        mRecordListAdapter.bindData(mRecordDatas);
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(LegworkMainActivity.this, R.string.active_failure_no_network,
                                  Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(LegworkMainActivity.this, (String) msg.obj,
                                  Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        SDKInitializer.initialize(getApplicationContext());
        super.onCreate(savedInstanceState, R.layout.legwork_main_layout);


    }

    private void initMap() {
        mBaiduMap = mMapView.getMap();
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaiduMap
              .setMyLocationConfigeration(new MyLocationConfiguration(
                    mCurrentMode, true, null));
        //设置是否显示比例尺控件
        mMapView.showScaleControl(false);
        //设置是否显示缩放控件
        mMapView.showZoomControls(false);
        // 删除百度地图LoGo
        mMapView.removeViewAt(1);

        UiSettings settings = mBaiduMap.getUiSettings();
        settings.setAllGesturesEnabled(false);   //关闭一切手势操作
        settings.setOverlookingGesturesEnabled(false);//屏蔽双指下拉时变成3D地图
        settings.setZoomGesturesEnabled(false);//获取是否允许缩放手势返回:是否允许缩放手势

        geoCoder = GeoCoder.newInstance();
        // geoCoder.setOnGetGeoCodeResultListener(this);

        // mBaiduMap.setOnMapStatusChangeListener(this);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        refreshLoction();
    }


    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mIvSign.setOnClickListener(this);
        mLlSearch.setOnClickListener(this);
        mTvOtherAddress.setOnClickListener(this);
        mLvAddress.setOnScrollListener(this);
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        mLvAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == mAddressListAdapter.getCount()) {
                    return;
                } else {
                    if (mRlLayout1.getVisibility() == View.GONE) {
                        mRlLayout1.setVisibility(View.VISIBLE);
                        mRlLayout2.setVisibility(View.GONE);
                        mLlSearchLayout.setVisibility(View.GONE);
                    }
                    if (flag == 0) {
                        Intent intent = new Intent(LegworkMainActivity.this, LegworkSignActivity.class);
                        intent.putExtra("group_id", mGroupId);
                        intent.putExtra("form_id", mFormId);
                        intent.putExtra("addressData", mAddressDatas.get(position));
                        startActivityForResult(intent,REQUEST_CODE_SIGN);
                    } else {
                        Intent result = new Intent();
                        result.putExtra("addressData", mAddressDatas.get(position));
                        setResult(RESULT_OK, result);
                        finish();
                    }
                }
            }
        });
        mLvRecord.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mRecordDatas == null || mRecordDatas.size() == 0) {
                    return;
                } else {
                    Intent intent = new Intent(LegworkMainActivity.this, LegworkDetailActivity.class);
//                    intent.putExtra("record_data", mRecordDatas.get(position));
                    intent.putExtra("record_datas", mRecordDatas);
                    intent.putExtra("page_index",position);
                    startActivity(intent);
                }
            }
        });

    }

    private void getIntentData() {
        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mFormId = intent.getStringExtra("form_id");
        if ("update".equals(intent.getAction())) {
            flag = 1;
            mLlSearchLayout.setVisibility(View.VISIBLE);
            mRlLayout1.setVisibility(View.GONE);
            mRlLayout2.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void initData() {
        mTvTitle.setText("外勤签到");
        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setText("刷新");
        mTvRight.setOnClickListener(this);
        View footerView = LayoutInflater.from(mActivity).inflate(R.layout.xlistview_footer, null);
        mFooterLayout = (LinearLayout) footerView.findViewById(R.id.xlistview_footer_content);
        mFooterText = (TextView) footerView.findViewById(R.id.xlistview_footer_hint_textview);
        mFooterProgress = (ProgressBar) footerView.findViewById(R.id.xlistview_footer_progressbar);
        mFooterLayout.setVisibility(View.GONE);
        mLvAddress.addFooterView(footerView);
        waitDlgShow();
        initMap();
        mAddressListAdapter = new LegworkAddressListAdapter(this);
        mLvAddress.setAdapter(mAddressListAdapter);
        mPoiSearch = PoiSearch.newInstance();

        mRecordListAdapter = new LegworkRecordListAdapter(mActivity);
        mLvRecord.setAdapter(mRecordListAdapter);
        getIntentData();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_ll_back:
                if (mRlLayout1.getVisibility() == View.VISIBLE) {
                    finish();
                } else {
                    if (flag == 0) {
                        mRlLayout1.setVisibility(View.VISIBLE);
                        mRlLayout2.setVisibility(View.GONE);
                        mLlSearchLayout.setVisibility(View.GONE);
                    } else {
                        finish();
                    }

                }
                break;
            case R.id.title_tv_right:
                waitDlgShow();
                refreshLoction();
                break;
            case R.id.ll_legwork_main_search_layout_click:
                float y = mLlSearch.getScrollY();
                int height = mLlSearch.getHeight();
                TranslateAnimation animation = new TranslateAnimation(0, 0, 0, -y);
                animation.setDuration(500);
                animation.setFillAfter(true);
                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        Intent search = new Intent(LegworkMainActivity.this, LegworkMapSearchActivity.class);
                        search.putExtra("latitude", latitude);
                        search.putExtra("longitude", longitude);
                        search.putExtra("group_id", mGroupId);
                        search.putExtra("form_id", mFormId);
                        search.putExtra("flag", flag);
                        startActivityForResult(search, MAP_SEARCH);
                    }
                });
                mLlRoot.startAnimation(animation);
                break;
            case R.id.tv_legwork_main_other_address:
                mLlSearchLayout.setVisibility(View.VISIBLE);
                mRlLayout1.setVisibility(View.GONE);
                mRlLayout2.setVisibility(View.VISIBLE);


                break;
            case R.id.iv_legwork_main_current_address_sign_in:
                Intent intent = new Intent(this, LegworkSignActivity.class);
                intent.putExtra("group_id", mGroupId);
                intent.putExtra("form_id", mFormId);
                AddressData addressData = new AddressData();
                addressData.setName("我的位置");
                addressData.setAddress(address);
                addressData.setLatitude(latitude);
                addressData.setLongitude(longitude);
                intent.putExtra("addressData", addressData);
                startActivityForResult(intent,REQUEST_CODE_SIGN);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case MAP_SEARCH:
                    AddressData addressData = (AddressData) data.getSerializableExtra("addressData");
                    /*latitude = addressData.getLatitude();
                    longitude = addressData.getLongitude();
                    //实例化一个地理编码查询对象
                    LatLng latLng = new LatLng(latitude, longitude);
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(latLng).zoom(18.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                    //设置反地理编码位置坐标
                    //发起反地理编码请求(经纬度->地址信息)
                    geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                            .location(latLng));*/
                    Intent result = new Intent();
                    result.putExtra("addressData", addressData);
                    setResult(RESULT_OK, result);
                    finish();
                    break;
                case REQUEST_CODE_SIGN:
                    refreshLoction();
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        // 退出时销毁定位
        if (mLocationUtil != null) {
            mLocationUtil.stopLocation();
            mLocationUtil.destoryLocation();
            mLocationUtil = null;
        }

        mMapView.onDestroy();
        mMapView = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        getLegworkListMsg();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    private void searchNeayBy() {
        PoiNearbySearchOption option = new PoiNearbySearchOption();
        // option.keyword(address);
        option.keyword("公司");
        option.sortType(PoiSortType.distance_from_near_to_far);
        option.location(new LatLng(latitude, longitude));
        /*if (radius != 0) {
            option.radius(radius);
        } else {*/
        option.radius(500);
        /*}*/

        option.pageCapacity(20);
        option.pageNum(pageIndex);
        mPoiSearch.searchNearby(option);

    }


    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        if (poiResult == null
              || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(LegworkMainActivity.this, "未找到结果", Toast.LENGTH_LONG)
                  .show();
            return;
        }
/*        if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
          *//*  mBaiduMap.clear();
            PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
            mBaiduMap.setOnMarkerClickListener(overlay);
            overlay.setData(poiResult);
            overlay.addToMap();
            overlay.zoomToSpan();*//*
            return;
        }
        if (poiResult.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            String strInfo = "在";
            for (CityInfo cityInfo : poiResult.getSuggestCityList()) {
                strInfo += cityInfo.city;
                strInfo += ",";
            }
            strInfo += "找到结果";
            Toast.makeText(LegworkMainActivity.this, strInfo, Toast.LENGTH_LONG)
                    .show();
        }*/
        if (pageIndex == 1) {
            mAddressDatas.clear();
            AddressData addressData = new AddressData();
            addressData.setName("我的位置");
            addressData.setAddress(address);
            addressData.setLatitude(latitude);
            addressData.setLongitude(longitude);
            mAddressDatas.add(addressData);
        }

        if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
            if (poiResult.getAllPoi() != null && poiResult.getAllPoi().size() > 0) {
                if (poiResult.getAllPoi() != null && poiResult.getAllPoi().size() > 0) {
                    for (int i = 0; i < poiResult.getAllPoi().size(); i++) {
                        count = poiResult.getAllPoi().size();
                        PoiInfo info = poiResult.getAllPoi().get(i);
                        AddressData addressData = new AddressData();
                        addressData.setCity(info.city);
                        addressData.setName(info.name);
                        addressData.setAddress(info.address);
                        addressData.setLatitude(info.location.latitude);
                        addressData.setLongitude(info.location.longitude);
                        addressData.setUid(info.uid);
                        mAddressDatas.add(addressData);
                    }

                }
                /*Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);*/
            }
            mAddressListAdapter.bindData(mAddressDatas);
            showFooterLayout(false);
            return;
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        switch (absListView.getId()) {
            case R.id.lv_legwork_main_address_list:
                if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
                    if (is_scrolling) {
                        if (count < pageSize) {
                            showFooterLayout(false);
                        } else {
                            ++pageIndex;
                            searchNeayBy();
                        }

                    }


                }
                break;
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        switch (absListView.getId()) {
            case R.id.lv_legwork_main_address_list:
                if ((firstVisibleItem + visibleItemCount == totalItemCount) && totalItemCount != 0) {
                    if (count < pageSize) {
                        showFooterLayout(false);
                    } else {
                        showFooterLayout(true);
                    }
                    is_scrolling = true;
                } else {
                    is_scrolling = false;
                }
                break;
        }
    }

    public void showFooterLayout(boolean isShow) {
        if (isShow) {
            mFooterLayout.setVisibility(View.VISIBLE);
            mFooterText.setText(this.getResources().getString(
                  R.string.xlistview_footer_hint_normal));
            mFooterProgress.setVisibility(View.VISIBLE);
        } else {
            mFooterLayout.setVisibility(View.GONE);

        }
    }


    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(LegworkMainActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                  .show();
        } else {
            Toast.makeText(LegworkMainActivity.this, poiDetailResult.getName() + ": " + poiDetailResult.getAddress(), Toast.LENGTH_SHORT)
                  .show();
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onBackPressed() {
        // super.onBackPressed();
        if (mRlLayout1.getVisibility() == View.VISIBLE) {
            finish();
        } else {
            mRlLayout1.setVisibility(View.VISIBLE);
            mRlLayout2.setVisibility(View.GONE);
            mLlSearchLayout.setVisibility(View.GONE);
        }
    }

    private void getLegworkListMsg() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_FORM_ID, mFormId));
        LegworkListMsg legworkListMsg = new LegworkListMsg(mHandler.obtainMessage(GET_LEGWORK_LIST_MSG), this);
        legworkListMsg.mApi = AsynHttpClient.API_EVENT_LEGWORK_LIST;
        legworkListMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(legworkListMsg);

    }


    private void refreshLoction() {
        if (mLocationUtil != null) {
            mLocationUtil.stopLocation();
            mLocationUtil.destoryLocation();
            mLocationUtil = null;
        }

        mLocationUtil = new LocationUtil(this);
        mLocationUtil.setListener(new LocationUtil.LocationStatus() {
            @Override
            public void onLocated(BDLocation location) {
                // map view 销毁后不在处理新接收的位置
                if (location == null || mMapView == null) {
                    return;
                }
                waitDlgDismiss();
                Log.d(Tag, "当前位置经纬度：latitude=" + location.getLatitude() + ",longitude=" + location.getLongitude() + ",address" + location.getAddress() + ",addrStr" + location.getAddrStr());
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                address = location.getAddrStr();
                mTvCAddress.setText(address);
                MyLocationData locData = new MyLocationData.Builder()
                      .accuracy(location.getRadius())
                      // 此处设置开发者获取到的方向信息，顺时针0-360
                      .direction(100).latitude(location.getLatitude())
                      .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                LatLng ll = new LatLng(location.getLatitude(),
                      location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                searchNeayBy();

            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mRlLayout1.getVisibility() == View.VISIBLE) {
                finish();
            } else {
                if (flag == 0) {
                    mRlLayout1.setVisibility(View.VISIBLE);
                    mRlLayout2.setVisibility(View.GONE);
                    mLlSearchLayout.setVisibility(View.GONE);
                } else {
                    finish();
                }

            }
        }
        return false;

    }

}
